package com.kgc.service.impl;

import com.kgc.dao.UserDao;
import com.kgc.entity.User;
import com.kgc.service.UserService;
import com.kgc.util.FileUtil;
import com.kgc.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Transactional(readOnly = true)
    @Override
    public User getUserByUsername(String username) {

        return userDao.getUserByUsername(username);
    }

    @Transactional(readOnly = true)
    @Override
    public List<User> listUsers(String name, String userRole, int currentPage) {
        Map<String,Object> paramMap = new HashMap<String,Object>();

        paramMap.put("start",(currentPage - 1) * 4);
        if(name != null && !"".equals(name)){
            paramMap.put("name",name);
        }
        if(!"0".equals(userRole)){
            paramMap.put("userRole",Integer.parseInt(userRole));
        }
        return userDao.listUsers(paramMap);
    }

    @Transactional(readOnly = true)
    @Override
    public int countUsers(String name, String userRole) {
        Map<String,Object> paramMap = new HashMap<String,Object>();

        if(name != null && !"".equals(name)){
            paramMap.put("name",name);
        }
        if(!"0".equals(userRole)){
            paramMap.put("userRole",Integer.parseInt(userRole));
        }
        return userDao.countUsers(paramMap);
    }

    @Transactional(readOnly = true)
    @Override
    public User getUserById(int id) {
        return userDao.getUserById(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int insertUser(User u) {
        return userDao.insertUser(u);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int deleteUserById(int id,String rootPath) {
        //删除图片
        User user = userDao.getUserById(id);
        //获取图片
        String cardPhotoPath = user.getCardphoto();
        //删除文件
        FileUtil.deleteFile(cardPhotoPath,rootPath);
        String wordPhotoPath = user.getWorkphoto();
        FileUtil.deleteFile(wordPhotoPath,rootPath);

        return userDao.deleteUserById(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int updateUser(User u) {
        return userDao.updateUser(u);
    }

    @Transactional(readOnly = true)
    @Override
    public int countUserByUsercode(String usercode) {
        return userDao.countUserByUsercode(usercode);
    }
}
